package com.happypets.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.happypets.model.ManagerBean;

/**
 * Servlet Filter implementation class CheckPowerFilter
 */
public class CheckPowerFilter implements Filter {

	public static Map<String,String> map;
	
	static{
		map = new HashMap<String,String>();
		
		map.put("pets", "宠物管理");
		map.put("user", "会员管理");
		map.put("manager", "员工管理");
		map.put("stats", "业务处理");
		map.put("deal", "营业分析");
		
	}
	
	
    public CheckPowerFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		
		if(session.getAttribute("manager")!=null){
			
			ManagerBean mb = (ManagerBean) session.getAttribute("manager");
			List<String> ps = mb.getPower();
			String url = req.getServletPath();
			
			String reg = url.substring(url.lastIndexOf("/")+1, url.indexOf("."));
			System.out.println("reg   ---   "+reg);
			if(reg.equals("index")||reg.equals("login")){
				chain.doFilter(request, response);
			}else{
				String flag = map.get(reg);
				if(ps.contains(flag)){
					chain.doFilter(request, response);
				}else{
					if(ps.contains("宠物管理") && reg.equals("category")){
						chain.doFilter(request, response);
					}else{
						resp.sendRedirect("index.html");
					}
				}
			}
			
		}else{
			chain.doFilter(request, response);
		}
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
